<?php

class LoginController {

    public function invoke() {
        $dir = dirname(__FILE__);
        $action = '';

        if (isset($_POST['hdAction'])) {
            $action = $_POST['hdAction'];
        }     
//        Utility::reload();      
      if ($action == 'login') {      
            $username = $_POST['txtUsername'];
            $Sys_user = $this->getSysUserByUsername($username);            
            if ($Sys_user != null) {
                $password = Utility::base64url_encode($_POST['txtPassword']);                
                if ($password == $Sys_user->getPassword()) {                    
                    $sessionNameList = array('sUserID','Username');
                    $sessionValueList = array($Sys_user->getId(),$Sys_user->getUsername());                    
                    Utility::createSession($sessionNameList, $sessionValueList);                    
                   echo 'OK';                   
                } else {
                    echo 'NOOK';
                }
            } else {
                echo 'NOOK';
            }            
             exit();            
        } 
        $viewFile = $dir . '/views/login.html';
        $xtemplate = new XTemplate($viewFile);
        $xtemplate->parse('main');
        $xtemplate->out('main');
    }

    private function getSysUserByUsername($username) {
        $db = new Database();
        try {
            $Sys_user = new Sys_user();
            $Sys_user->setUsername($username);
            $Sys_user->getByUsername($db);
            $db->submitChanges();
            return $Sys_user;
        } catch (PDOException $exc) {
            echo $exc->getMessage();
            $db->rollback();
            exit();
        }
    }

}
